package com.itmuch.usercenter.service.user;

import com.itmuch.usercenter.dao.bonus_event_log.BonusEventLogMapper;
import com.itmuch.usercenter.dao.user.UserMapper;
import com.itmuch.usercenter.domain.dto.messaging.UserAddBonusMsgDTO;
import com.itmuch.usercenter.domain.dto.user.UserLoginDTO;
import com.itmuch.usercenter.domain.entity.bonus_event_log.BonusEventLog;
import com.itmuch.usercenter.domain.entity.user.User;
import com.itmuch.usercenter.utils.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private BonusEventLogMapper bonusEventLogMapper;

    public User findById(Integer id){
        log.info("触发这个效果");
        return userMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addBonus(UserAddBonusMsgDTO userAddBonusMsgDTO) {
        //查找用户实体
        User user = userMapper.selectByPrimaryKey(userAddBonusMsgDTO.getUserId());
        //加分
        Integer bonus = userAddBonusMsgDTO.getBonus();
        user.setBonus(user.getBonus()+ bonus);
        userMapper.updateByPrimaryKeySelective(user);
            
        
        
        //记录日志
        bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(user.getId())
                        .event(bonus>0?"事件":"兑换")
                        .description(bonus>0?"事实":"扣除分数成功")
                        .createTime(new Date())
                        .value(bonus)
                        .build()
        );
        log.info("增加积分成功"+  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    public User login(UserLoginDTO userLoginDTO, String openId) {

        User user = userMapper.selectOne(
                User.builder()
                        .wxId(openId)
                        .build()
        );
        if (user != null) {
            return user;
        }else {
            User userToSave = User.builder()
                    .wxId(openId)
                    .avatarUrl(userLoginDTO.getAvatarUrl())
                    .bonus(300)
                    .roles("user")
                    .wxNickname(userLoginDTO.getWxNickname())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            userMapper.insertSelective(
                    userToSave
            );
            log.info(userToSave.toString());
            return userToSave;
        }
    }
}
